package com.seari.custody.handler;

import com.seari.custody.exception.BIZException;
import com.seari.custody.pojo.MessageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 参数绑定时候抛出的异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public MessageBean handleBindException(MethodArgumentNotValidException ex) {
        log.error("参数校验异常", ex);
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());
        return MessageBean.fail(String.join(",", errors), "");
    }

    @ExceptionHandler(value = {IllegalArgumentException.class, BindException.class})
    public MessageBean handleBindException(Exception ex) {
        log.error("参数校验异常", ex);
        return MessageBean.fail(ex.getMessage(), "");
    }

    @ExceptionHandler(value = BIZException.class)
    public MessageBean bizException(BIZException ex) {
        log.error("业务异常", ex);
        return MessageBean.fail(ex.getMessage(), "");
    }

    /**
     * @param ex
     * @return
     */

    @ExceptionHandler(value = Exception.class)
    public MessageBean handleException(Exception ex) {
//        if(ex instanceof BlogRuntimeException){
//            log.error( "抛出自定义异常",ex);
//        }else {
        log.error("系统内部异常", ex);
//        }
        return MessageBean.fail("系统异常", "");
    }

}
